package com.mm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mm.constant.BusinessConstant;
import com.mm.dao.RecruitMapper;
import com.mm.exception.ServiceException;
import com.mm.model.Recruit;
import com.mm.service.RecruitService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static javafx.scene.input.KeyCode.E;
import static javafx.scene.input.KeyCode.J;

/**
 * 招聘service
 *
 * @date 2018/7/19 16:43
 */
@Service(value = "recruitService")
public class RecruitServiceImpl implements RecruitService {
	@Autowired
	private RecruitMapper recruitMapper;
	/**
	 * 保存招聘信息
	 *
	 * @param jsonData String
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void saveRecruit(String jsonData) throws ServiceException {
		if (StringUtils.isBlank(jsonData)) {
			throw new ServiceException("输入参数不能为空");
		}
		JSONObject dataJsonObj = JSON.parseObject(jsonData);
		//获取招聘信息
		String recruitJsonString = dataJsonObj.getString(BusinessConstant.JSON_KEY_RECRUIT);
		if (StringUtils.isBlank(recruitJsonString)) {
			throw new ServiceException("招聘信息不能为空");
		}
		Recruit recruit = JSON.parseObject(recruitJsonString, Recruit.class);
		recruit.setAuditStatus(BusinessConstant.AUDIT_STATUS_DOING);
		recruit.setAddTime(System.currentTimeMillis());
		recruitMapper.insertRecruit(recruit);
		//获取图片信息
		String pictureIds = dataJsonObj.getString(BusinessConstant.JSON_KEY_PICTURE_IDS);
		if (StringUtils.isNotBlank(pictureIds)) {
			saveRecruitPicture(recruit.getRecruitId(), pictureIds);
		}
	}

	/**
	 * 更新招聘
	 *
	 * @param recruit Recruit
	 */
	@Override
	public void updateRecruit(Recruit recruit) {
		if (recruit != null) {
			recruitMapper.updateRecruitById(recruit);
		}
	}

	/**
	 * 获取招聘
	 *
	 * @param recruitId 招聘ID
	 * @return Recruit
	 */
	@Override
	public Recruit getOneRecruitById(Long recruitId) {
		if (recruitId != null) {
			return recruitMapper.getOneRecruitById(recruitId);
		}
		return null;
	}

	/**
	 * 通过招聘ID删除招聘
	 *
	 * @param recruitId 招聘ID
	 */
	@Override
	public void deleteRecruitById(Long recruitId) {
		if (recruitId != null) {
			recruitMapper.deleteRecruitById(recruitId);
		}
	}

	/**
	 * 保存招聘图片关系
	 * @param recruitId  招聘第
	 * @param pictureIds 图片ID字符串(以","分割)
	 * @throws ServiceException
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void saveRecruitPicture(Long recruitId, String pictureIds) throws ServiceException {
		if (recruitId == null || StringUtils.isBlank(pictureIds)) {
			throw new ServiceException("输入参数不能为空");
		}
		String[] pictureIdArray = pictureIds.split(",");
		recruitMapper.insertRecruitPicture(recruitId, pictureIdArray);
	}
}
